package action;

import Impl.UserDaoImpl;
import entity.User;

import javax.naming.Name;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class RegisterAction extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserDaoImpl userDao = new UserDaoImpl();
        System.out.println("---------正在执行RegisterAction------------");
        // 用户提交的用户名
        String uid = request.getParameter("username");
        // 用户提交密码
        String pwd = request.getParameter("pwd");
//        用户提交的确认密码
        String pwd_r = request.getParameter("pwd_repeat");
//        手机号
        String phone =request.getParameter("phone");
        String email = request.getParameter("mailcode");
        String province = request.getParameter("province");
        String city = request.getParameter("city");
        String area = request.getParameter("area");
//        判断两次密码是否一致
        if (!pwd.equals(pwd_r)){
            request.setAttribute("message","两次密码输入不一样");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }
        if(userDao.getUserByCondition(phone) != null){
            request.setAttribute("message","该用户已存在");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }
//        String phone, String email, String password, String name, String province, String city, String area, String school, String grade
        User user=new User(phone,email,pwd,uid,province,city,area,"未填写","未填写");
        user.setImg_path("default_photo.gif");
        userDao.create(user);
        userDao.save(user);
        HttpSession session =request.getSession();
        user=userDao.getUserByCondition(phone);
        session.setAttribute("user",user);
        System.out.println("注册成功！");
        request.getRequestDispatcher("/header.jsp").forward(request,response);
//        response.sendRedirect("login.jhtml");
    }
}
